﻿using AuthenticationAPI.Models.DbContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AuthenticationAPI.Models.Utility
{
    public class UserHelper
    {
        public static userInfo GetUserInfo(User user)
        {

            using (var userDb = new AuthenticationEntities())
            using (var prjDb = new MetroProjectsEntities())
            {
                var info = new userInfo()
                {
                    authentication = user.Authentication,
                    mail = user.Mail,
                    phone = user.Phone,
                    userName = user.UserName,
                    realName = user.RealName,
                    corporation = user.Corporation,
                    department = user.Department,
                    avatar = user.Avatar,
                    authorzedLevel = UserHelper.getAuthorizedLevel(user),
                    authorizedDepartments = UserHelper.getAuthorizedDepartment(user),
                    wechatId = user.WechatId
                };
                return info;
            }
        }

        public static List<string> getAuthorizedLevel(User user)
        {
            var authors = new string[] { "Administrator", "CorpAdministrator", "DepartAdministrator", "Manager", "User" };
            if (user.Authentication == "Manager" || user.Authentication == "User" || user.Authentication == "Administrator")
            {
                return new List<string>();
            }
            else if (user.Authentication == "Owner")//业主管理员
            {
                return new string[] { "Owner", "User" }.ToList();
            }
            else
            {
                var index = authors.ToList().IndexOf(user.Authentication);
                if (index >= 0)
                {
                    return authors.Skip(index + 1).ToList();
                }
                else
                {
                    return new List<string>();
                }
            }
        }

        public static List<string> getAuthorizedDepartment(User user)
        {
            using (var db = new AuthenticationEntities())
            {
                if (user.Authentication == "CorpAdministrator" || user.Authentication == "Owner")
                {
                    var list = (from p in db.Corporation
                                join q in db.Department
                                on p.UID equals q.CorpId
                                where p.Remark == user.Corporation
                                select q.DepartmentName).ToList();
                    return list;
                }
                else if (user.Authentication == "DepartAdministrator")
                {
                    return new List<string>(new string[] { user.Department });
                }
                else
                {
                    return new List<string>();
                }
            }

        }


        /// <summary>
        /// 获取一个用户能够管理的用户列表
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static List<userInfo> GetAuthorizedUsers(string userName)
        {
            using (var db = new AuthenticationEntities())
            {
                var uu = db.User.Single(p => p.UserName == userName);
                //先得到信息更全的userinfo
                var user = UserHelper.GetUserInfo(uu);
                //根据userinfo中的可分配部门和可分配权限,查找旗下的所有用户
                var allUsers = (from p in db.User
                                where p.Corporation == user.corporation
                                select p).ToList();
                if (user.authentication == "Owner")
                {
                    user.authorzedLevel = new List<string>(new string[] { "User" });
                }
                var myUsers = (from u in allUsers
                               where user.authorzedLevel.IndexOf(u.Authentication) >= 0
                                   && user.authorizedDepartments.IndexOf(u.Department) >= 0
                               orderby u.Department
                               select new userInfo()
                               {
                                   authentication = u.Authentication,
                                   userName = u.UserName,
                                   realName = u.RealName,
                                   phone = u.Phone,
                                   mail = u.Mail,
                                   department = u.Department,
                                   corporation = u.Corporation,
                                   avatar = u.Avatar,
                                   freeze = u.Freeze,
                                   authorizedProjectList = UserHelper.GetAuthorizedProjects(u.UserName)
                               }).ToList();

                return myUsers;
            }
        }

        /// <summary>
        /// 获取一个用户的权限项目
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        public static List<int> GetAuthorizedProjects(string userName)
        {
            using (var userDb = new AuthenticationEntities())
            using (var prjDb = new MetroProjectsEntities())
            {

                var user = userDb.User.SingleOrDefault(p => p.UserName == userName);
                var prjList = new List<int>();
                if (user.Authentication == "Administrator")
                {
                    prjList = prjDb.MonitorProjectExtraInfo.Select(p => p.PrjId).ToList();
                }
                else if (user.Authentication == "CorpAdministrator")
                {
                    prjList = prjDb.MonitorProjectExtraInfo.Where(p => p.ConstructionCorp == user.Corporation).Select(p => p.PrjId).ToList();
                }
                else if (user.Authentication == "Owner")
                {
                    prjList = prjDb.MonitorProjectExtraInfo.Where(p => p.OwnerCorp == user.Corporation).Select(p => p.PrjId).ToList();
                }
                else if (user.Authentication == "DepartAdministrator")
                {
                    prjList = prjDb.MonitorProjectExtraInfo.Where(p => p.ConstructionCorp == user.Corporation
                   && p.Department == user.Department).Select(p => p.PrjId).ToList();
                }
                else if (user.Authentication == "Manager")
                {
                    prjList = userDb.AuthorizedProject.Where(p => p.UserName == userName).Select(p => p.PrjId).ToList();
                }
                else if (user.Authentication == "User")
                {
                    prjList = userDb.AuthorizedProject.Where(p => p.UserName == userName).Select(p => p.PrjId).ToList();
                }
                return prjList;
            }
        }


        public static string avatarGenerator()
        {
            var random = new Random();
            var x = random.Next(1, 35);
            var baseAvatarUrl = string.Format("http://jigi-imgs.qiniudn.com/男_{0}.JPG",
                    x.ToString("000"));
            return baseAvatarUrl;
        }


        public static List<ProjectTypeEnum> GetAuthorizedProjectTypes(string userName)
        {
            using (var db = new MetroProjectsEntities())
            {
                var prjList = UserHelper.GetAuthorizedProjects(userName);

                var datas = from t in db.ProjectTypeEnums.OrderBy(p => p.Sequence)
                            join
                            p in db.Projects.Where(p => prjList.Contains(p.PrjId))
                            on t.ProjectType equals p.ProjectType into gs
                            where gs.Count() > 0
                            select t;
                return datas.ToList();
            }
        }
    }
}